/*
 * The MIT License
 *
 * Copyright 2012 Anonymous.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package pentomino.ui;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.TimeUnit;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
import pentomino.logic.PentominoGame;

/**
 *
 * Represents a status panel.
 */
public class StatusBar extends JPanel {
    
    private final PentominoGame game;
    private Timer timer;
    
    /*============== Constructors ==============*/
    
    /**
     * Creates an instance of the StatusBar class by default.
     */
    public StatusBar(PentominoGame pentominoGame)
    {
        super();
        
        game = pentominoGame;
        timer = new Timer(100, null);
        timer.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                game.incElapsedTime(timer.getDelay());
                repaint();
            }
        });

        setBorder(new EmptyBorder(0, 10, 0, 10));
    }
    
    /*============== Methods ==============*/
    
    /**
     * Starts the watching (time counting).
     */
    public void startWatch()
    {
        game.setActionsCount(0);
        game.setElapsedTime(0);
        timer.start();
    }
    
    /**
     * Stops the watching (time counting).
     */
    public void stopWatch()
    {
        timer.stop();
    }
    
    /**
     * Gets the current game actions count.
     * 
     * @param actions number of actions
     */
    private String getActionsLabel()
    {
        int actions = game.getActionsCount();
        
        return String.format("Actions: %d", actions);
    }
    
    /**
     * Gets the timer information.
     * 
     * @param time an elapsed time in milliseconds
     */
    private String getTimeLabel()
    {
        long time = game.getElapsedTime();
        long totalSeconds = TimeUnit.SECONDS.convert(time, TimeUnit.MILLISECONDS);       
        long seconds = totalSeconds % 60;      
        totalSeconds /= 60;
        long minutes = totalSeconds % 60;
        long hours = totalSeconds /= 60;
        
        StringBuilder sb = new StringBuilder();
        
        sb.append("Time: ");
        
        if (hours > 0)
            if (hours > 9)
                sb.append(String.format("%d:", hours));
            else
                sb.append(String.format("0%d:", hours));
        else
            sb.append("00:");
            
        if (minutes > 0)
            if (minutes > 9)
                sb.append(String.format("%d:", minutes));
            else
                sb.append(String.format("0%d:", minutes));
        else
            sb.append("00:");
        
        if (seconds > 9)
            sb.append(String.format("%d", seconds));
        else
            sb.append(String.format("0%d", seconds));
        
        sb.append(String.format(".%d", (time % 1000) / 100));
        
        return sb.toString();
    }
    
    /**
     * Draws the status bar content.
     * @param g 
     */
    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        
        Graphics2D g2d = (Graphics2D)g;
        
        GradientPaint gradient = new GradientPaint(
                0, 0, getBackground(),
                0, getHeight(), Color.white);
        
        Color c = g2d.getColor();
        
        g2d.setPaint(gradient);
        g2d.fillRect(0, 0, getWidth(), getHeight());
        g2d.setColor(Color.lightGray);
        g2d.drawLine(0, 0, getWidth(), 0);
        
        gradient = new GradientPaint(
                0, 0, Color.gray,
                0, getHeight() / 5, getBackground());
        
        g2d.setPaint(gradient);
        g2d.fillRect(0, 1, getWidth(), getHeight() / 5);
        
        if (!game.hasStarted() && !game.hasFinished())
        {
            g2d.setColor(getForeground());
            g2d.setFont(new Font("Arial", Font.BOLD, 18));
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.drawString(getActionsLabel(), 25, 30);
            g2d.drawString(getTimeLabel(), getWidth() / 2 + 25, 30);
        }
        else if (game.hasFinished())
        {
            g2d.setColor(getForeground());
            g2d.setFont(new Font("Arial", Font.BOLD, 24));
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.drawString("Solved!", getWidth() / 2 - 48, getHeight() / 2 + 8);
        }
        
        g2d.setColor(c);
    }
}
